package main.java.study.websocket;
import lombok.Getter;

import javax.websocket.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

@ClientEndpoint
public class MultiServerWebSocketClient {

    private Session session;
    private final URI serverURI;
    private boolean stopReconnect = false; // 用于控制是否停止重连
    @Getter
    private static final List<String> responseList = Collections.synchronizedList(new ArrayList<>());

    public MultiServerWebSocketClient(String serverURI) {
        this.serverURI = URI.create(serverURI);
        connect();
    }

    // 封装连接逻辑
    public void connect() {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(this, serverURI);
            System.out.println("Connected to server: " + serverURI);
        } catch (Exception e) {
            System.err.println("Failed to connect to server: " + serverURI);
            e.printStackTrace();
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("WebSocket connection opened: " + serverURI);
    }

    @OnMessage
    public void onMessage(String message) {
//        System.out.println("Received message from " + serverURI + ": " + message);
        // 如果不是json格式，则直接返回
        if (!message.startsWith("{") ||!message.endsWith("}")) {
            return;
        }
        responseList.add(message); // 将收到的消息添加到集合中
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        System.out.println("Connection closed: " + reason);
        this.session = null;
        if (!stopReconnect) {
            scheduleReconnect(); // 尝试重连
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("Error occurred at " + serverURI + ": " + throwable.getMessage());
    }

    public void sendMessage(String message) {
        if (session != null && session.isOpen()) {
            session.getAsyncRemote().sendText(message);
            System.out.println("Message sent to " + serverURI + ": " + message);
        } else {
            System.err.println("Unable to send message to " + serverURI + ": Connection is closed");
        }
    }

    public static void clearResponseList() {
        responseList.clear();
    }

    private void scheduleReconnect() {
        // 使用线程池延迟重连
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.schedule(() -> {
            System.out.println("Reconnecting to server...");
            connect();
        }, 5, TimeUnit.SECONDS); // 5 秒后尝试重连
        scheduler.shutdown();
    }


}

